package com.cloud.calendar.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cloud.calendar.model.CalendarEvent;
import com.cloud.platform.IDao;
import com.cloud.platform.util.Constants;
import com.cloud.platform.util.StringUtil;

@Component
public class CalendarService {

	@Autowired
	private IDao dao;
	
	/**
	 * update calendar event
	 * 
	 * @param eventId
	 * @param startDate
	 * @param endDate
	 */
	public void updateEvent(String eventId, String startDate, String endDate) {
		
		if(StringUtil.isNullOrEmpty(eventId, startDate)) {
			return;
		}
		
		CalendarEvent ce = (CalendarEvent) dao.getObject(CalendarEvent.class, eventId);
		
		ce.setStartDate(startDate);
		ce.setEndDate(endDate);
		
		dao.saveObject(ce);
	}
	
	/**
	 * search user calendar events
	 * 
	 * @param userId
	 * @return
	 */
	public List<CalendarEvent> searchEvents(String userId) {
	
		if(StringUtil.isNullOrEmpty(userId)) {
			return new ArrayList();
		}
		
		// search all calendar events
		String hql = "select c,t.name from CalendarEvent c,Task t where c.uid = ? and c.taskId = t.id";
		List<Object[]> list = dao.getAllByHql(hql, userId);
		
		// conbine task name
		CalendarEvent ce = null;
		List<CalendarEvent> result = new ArrayList();
		
		for(Object[] o : list) {
			ce = (CalendarEvent) o[0];
			ce.setTaskName((String) o[1]);
			
			result.add(ce);
		}
		
		return result;
	}
	
	/**
	 * save calender event
	 * 
	 * @param startDate
	 * @param taskId
	 * @return
	 */
	public String saveEvent(String userId, String startDate, String taskId) {
		
		if(StringUtil.isNullOrEmpty(userId, startDate, taskId)) {
			return "";
		}
		
		// create new calendar event
		CalendarEvent ce = new CalendarEvent();
		
		ce.setId(Constants.getID());
		ce.setUid(userId);
		ce.setTaskId(taskId);
		ce.setStartDate(startDate);
		
		// save calendar event
		dao.saveObject(ce);
		
		return ce.getId();
	}

	public IDao getDao() {
		return dao;
	}

	public void setDao(IDao dao) {
		this.dao = dao;
	}
}
